import React from 'react'
import { ScrollView, View } from '@tarojs/components'
import { useState, useEffect } from 'react'
import env from '../../store/env.config'
import MyGrid from './child/MyGrid'
import MyTitle from './child/MyTitle'
import MySearch from './child/MySearch'
import Taro from '@tarojs/taro'
import './index.scss'

const Index: React.FC<any> = ({}) => {
  const [dataSource, setDataSource] = useState([])
  const [userInfo, setUserInfo] = useState({} as any)
  const [refresherTriggered, setRefresherTriggered] = useState(true)

  const [refresh, setRefresh] = useState(0)
  useEffect(() => {
    getUserInfo()
  }, [])

  useEffect(() => {
    getGoodsTypeList()
  }, [userInfo])

  const getGoodsTypeList = () => {
    Taro.request({
      url: `${env.domain}/species/list`,
      data: {
        page: 1,
        pageSize: 10000,
        dictType: 'goods',
        parentId: 0,
        token: userInfo['auth'],
      },
      success: (res) => {
        setRefresherTriggered(false)
        setDataSource(res?.data?.data?.recode)
        setRefresh(refresh + 1)
      },
    })
  }

  const getUserInfo = () => {
    Taro.getStorage({
      key: 'userInfo',
      success: (res) => {
        setUserInfo(res.data)
      },
    })
  }

  return (
    <ScrollView
      scrollY
      refresherEnabled={true}
      refresherBackground='#555555'
      enhanced
      enableFlex
      refresherTriggered={refresherTriggered}
      onRefresherRefresh={() => {
        setRefresherTriggered(true)
        getGoodsTypeList()
      }}
    >
      <View className='index-box'>
        <View>
          <MySearch userInfo={userInfo} />
        </View>
        <View style={{ paddingTop: '8px' }}></View>
        {dataSource?.map((item: any) => {
          return (
            <>
              <MyTitle title={item.title} />
              <View>
                <MyGrid
                  parentId={item.id}
                  userInfo={userInfo}
                  refresh={refresh}
                />
              </View>
            </>
          )
        })}
      </View>
    </ScrollView>
  )
}

export default Index
